<script setup lang="tsx">
import { NButton, NPopconfirm, NSpace, NSwitch } from "naive-ui";
import type { DataTableColumns, FormInst } from "naive-ui";
import TableModal from "./components/TableModal.vue";

import {
  changeRoleStatus,
  delRole,
  listRole,
  roleMenuTreeselect
} from "@/service/api/role";
import { useBoolean, useLoading } from "@/hooks";

const roleList = ref([]);
const formRef = ref<FormInst | null>();
const initialParams = {
  pageNum: 1,
  pageSize: 10,
  roleName: "",
  roleKey: "",
};
const params = ref({ ...initialParams });
const total = ref(0);
const { loading, startLoading, endLoading } = useLoading(false);
const { bool: visible, setTrue: openModal } = useBoolean(false);
type ModalType = "add" | "edit";
const modalType = ref<ModalType>("add");
const editData = ref(null);

const columns: DataTableColumns = [
  {
    title: "角色名称",
    align: "center",
    key: "roleName",
  },
  {
    title: "权限字符",
    align: "center",
    key: "roleKey",
  },
  {
    title: "显示顺序",
    align: "center",
    key: "roleSort",
  },
  {
    title: "创建时间",
    align: "center",
    key: "createTime",
  },
  {
    title: "状态",
    align: "center",
    key: "status",
    render: (row) => {
      const rowData:any = row;
      if (rowData.admin) return null;
      return (
        <NSwitch
          value={rowData.status}
          checkedValue={"0"}
          onUpdateValue={(status) => handleStatusChange(rowData.roleId, status)}
        >
          {{ checked: () => "启用", unchecked: () => "禁用" }}
        </NSwitch>
      );
    },
  },
  {
    title: "操作",
    align: "center",
    key: "actions",
    render: (row) => {
      const rowData:any = row;
      if (rowData.admin) return null;
      return (
        <NSpace justify="center">
          <NButton size="small" type="warning" onClick={() => handleEditTable(rowData)}>
            编辑
          </NButton>
          <NPopconfirm onPositiveClick={() => sendMail(rowData.roleName,rowData.roleId)}>
            {{
              default: () => "确认删除",
              trigger: () => (
                <NButton
                  size="small"
                  type="error"
                >
                  删除
                </NButton>
              ),
            }}
          </NPopconfirm>
        </NSpace>
      );
    },
  },
];
// 列表
async function getRoleList() {
  startLoading();
  await listRole(params.value).then((res: any) => {
    roleList.value = res.rows;
    total.value = res.total;
    endLoading();
  });
}
// 编辑
async function handleEditTable(rowData: any) {
  rowData.roleSort = Number(rowData.roleSort)
  await getDefMenuIds(rowData);
  await setEditData(rowData);
  setModalType("edit");
  openModal();
}
// 添加
function handleAddTable() {
  openModal();
  setModalType("add");
}
// 检索
function handleQuery() {
  params.value.pageNum = 1;
  getRoleList();
}
// 重置
function handleResetSearch() {
  params.value = { ...initialParams };
  getRoleList();
}
// 分页
function changePage(page: number, size: number) {
  params.value.pageNum = page;
  params.value.pageSize = size;
  getRoleList();
}
// 修改状态
function handleStatusChange(roleId: number, status: boolean) {
  const s = status === false ? "1" : "0";
  const text = s === "0" ? "启用" : "禁用";
  window.$dialog.warning({
    title: `提醒`,
    content: `确定要${text}该用户吗？`,
    positiveText: "确定",
    negativeText: "取消",
    onPositiveClick: () => {
      changeRoleStatus(roleId, s).then(() => {
        window.$message.success(`${text}成功`);
        getRoleList();
      });
    },
    onNegativeClick: () => {
      status = s === "0";
    },
  });
}
//
function setModalType(type: ModalType) {
  modalType.value = type;
}
function setEditData(data: any | null) {
  editData.value = data;
}

function sendMail(roleName: string,roleId:number) {
  delRole(roleId).then(() => {
    window.$message.success(`删除角色:${roleName}`);
    getRoleList();
  });
}

// 查询角色菜单列表
async function getDefMenuIds(rowData:any) {
  const roleId = rowData.roleId;
  await roleMenuTreeselect(roleId).then((res: any) => {
    rowData.menuIds = res.checkedKeys;
  });
}
function handleRefresh() {
  getRoleList();
}
getRoleList();
</script>

<template>
  <NSpace vertical size="large">
    <n-card>
      <n-form ref="formRef" :model="params" label-placement="left" :show-feedback="false">
        <n-grid :x-gap="30" :cols="4">
          <n-form-item-gi label="角色名称" path="roleName">
            <n-input v-model:value="params.roleName" placeholder="请输入" />
          </n-form-item-gi>
          <n-form-item-gi label="权限字符" path="roleKey">
            <n-input v-model:value="params.roleKey" placeholder="请输入" />
          </n-form-item-gi>
          <n-form-item-gi>
            <NButton type="primary" @click="handleQuery">
              <template #icon>
                <icon-park-outline-search />
              </template>
              搜索
            </NButton>
            <NButton strong secondary @click="handleResetSearch">
              <template #icon>
                <icon-park-outline-redo />
              </template>
              重置
            </NButton>
          </n-form-item-gi>
        </n-grid>
      </n-form>
    </n-card>
    <n-card>
      <NSpace vertical size="large">
        <div class="flex gap-4">
          <NButton type="primary" @click="handleAddTable">
            <template #icon>
              <icon-park-outline-add-one />
            </template>
            新建
          </NButton>
        </div>
        <n-data-table :columns="columns" :data="roleList" :loading="loading" />
        <Pagination :count="total" @change="changePage" v-if="total > params.pageSize" />
        <TableModal
          v-model:visible="visible"
          :type="modalType"
          :modal-data="editData"
          @refresh="handleRefresh"
        />
      </NSpace>
    </n-card>
  </NSpace>
</template>
